package com.guoqi.keepsign

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.donkor.deepnight.utils.showToast
import com.guoqi.keepsign.bxs.BxsTabUI
import com.guoqi.keepsign.kb.KbTabUI
import com.guoqi.keepsign.mzt.MztTabUI
import kotlinx.android.synthetic.main.content_main_ui.*
import kotlinx.android.synthetic.main.ui_main.*
import java.util.*


class MainUI : AppCompatActivity() {


    var count = 0

    companion object {
        var hasAllPermissions: Boolean = false
        val PERMISSIONS_STORAGE = arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE")
    }

    private var permissionListener = object : PermissionListener {
        override fun granted() {

        }

        override fun denied(deniedList: List<String>) {
            if (deniedList.isNotEmpty()) {
                showPermissionManagerDialog(this@MainUI, deniedList as ArrayList<String>)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.ui_main)
        requestRuntimePermissions(PERMISSIONS_STORAGE, permissionListener)
        val decorView = window.decorView
        val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        decorView.systemUiVisibility = option
        window.statusBarColor = Color.TRANSPARENT

        setSupportActionBar(toolbar)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "打卡成功", Snackbar.LENGTH_LONG).show()
            fab.setImageResource(R.mipmap.ic_sign_done)
            fab.backgroundTintList = resources.getColorStateList(R.color.colorAccent)
            fab.isEnabled = false
        }
        tv_bxs.setOnClickListener {
            startActivity(Intent(this, BxsTabUI::class.java))
        }
        tv_mzt.setOnClickListener {
            startActivity(Intent(this, MztTabUI::class.java))
        }
        tv_kb.setOnClickListener {
            startActivity(Intent(this, KbTabUI::class.java))
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main_ui, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_more -> {
                count++
                if (count > 3) {
                    tv_kb.visibility = View.VISIBLE
                }
                true
            }
            R.id.action_export -> {
                showToast("导出")
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    /**
     * 申请权限
     */
    private fun requestRuntimePermissions(permissions: Array<String>, listener: PermissionListener) {
        val permissionList = ArrayList<String>()
        // 遍历每一个申请的权限，把没有通过的权限放在集合中
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !== PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission)
            } else {
                permissionListener?.granted()
            }
        }
        // 继续申请权限
        if (permissionList.isNotEmpty()) {
            hasAllPermissions = false
            ActivityCompat.requestPermissions(this, permissionList.toTypedArray(), 1)
        } else {
            //已获取全部权限
            hasAllPermissions = true
        }
    }


    /**
     * 申请后的处理
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (grantResults.isNotEmpty() && permissionListener != null) {
            val deniedList = ArrayList<String>()
            // 遍历所有申请的权限，把被拒绝的权限放入集合
            for (i in grantResults.indices) {
                val grantResult = grantResults[i]
                if (grantResult == PackageManager.PERMISSION_GRANTED) {
                    permissionListener?.granted()
                } else {
                    //var alwaysDenied = hasAlwaysDeniedPermission(this, permissions[i])
                    deniedList.add(permissions[i])
                }
            }
            if (deniedList.isNotEmpty()) {
                permissionListener?.denied(deniedList)
            }
        }
    }

    interface PermissionListener {
        fun granted()
        fun denied(deniedList: List<String>)
    }

    /**
     * 显示权限弹框提示
     */
    fun showPermissionManagerDialog(context: Context, permissions: ArrayList<String>) {
        AlertDialog.Builder(context).setTitle("权限被禁用")
                .setMessage("请在 设置-应用管理-" + context.getString(R.string.app_name) + "-权限管理, 打开权限!")
                .setCancelable(false)
                .setNegativeButton("取消") { _, _ ->
                    run {
                        requestRuntimePermissions(permissions.toTypedArray(), permissionListener)
                    }
                }
                .setPositiveButton("去设置") { _, _ ->
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                    intent.data = Uri.fromParts("package", context.packageName, null)
                    startActivityForResult(intent, 1000)
                    Toast.makeText(this@MainUI, "请授予应用存储权限", Toast.LENGTH_SHORT).show()
                }.show()
    }
}
